//link in cmake:
//  target_link_libraries(${APP_DATACOLLECT} PRIVATE event) #被依赖项必修放在后面等价于 -uuid
//apt install
//  apt install libevent-dev
//  apt list --installed |grep "event"
//sample code.
//  more desc:
//  可参考：https://blog.csdn.net/twicave/article/details/148706718?spm=1001.2014.3001.5501

#include <assert.h>
#include <event2/event.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>


struct event_base *base = NULL;
struct event *ev = NULL;

void callback_fn_child_process_exit(evutil_socket_t fd, short events, void *arg) {
    int status;

    struct event_base *base = (struct event_base *)arg;  // 获取 base
    pid_t pid = waitpid(-1, &status, WNOHANG); //等待任一个
    if (pid != 0) {
        gpid_unregister_pid(pid);
        //printf("Command exited with status: %d\n", WEXITSTATUS(status));
    }
    if(gpid_is_all_process_exit()){
        //mosquitto进程永远不会退出 TODO:CHECK
        event_base_loopbreak(base); //退出event loop(event_base_dispatch退出)
    }
}

void gpid_daemon_create()
{
    //注册进程退出钩子
    base = event_base_new();
    // 注册子进程退出事件（需信号处理）
    ev = evsignal_new(base, SIGCHLD, callback_fn_child_process_exit, base);
    event_add(ev, NULL);
}
void gpid_daemon_loop_forever()
{
    event_base_dispatch(base); // 事件循环
}
void gpid_daemon_destory()
{
    while(!gpid_is_all_process_exit())
    {
        usleep(1000);
    }
    //取消注册进程钩子
    event_free(ev);
    event_base_free(base);
}